﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.ObjectBuilder2;

namespace MetaContainer.Unity
{
   /// <summary>
   /// Represents a strategy for mapping build keys in the build up operation.
   /// </summary>
   internal class FactoryBuildKeyMappingStrategy : BuilderStrategy
   {
      private readonly HashSet<Type> _factoryProducedTypes = new HashSet<Type>();

      internal void RegisterFactoryProducedType(Type t)
      {
         _factoryProducedTypes.Add(t);
      }      

      /// <summary>
      /// Called during the chain of responsibility for a build operation.  Looks for the <see cref="IBuildKeyMappingPolicy"/>
      /// and if found maps the build key for the current operation.
      /// </summary>
      /// <param name="context">The context for the operation.</param>
      public override void PreBuildUp(IBuilderContext context)
      {
         NamedTypeBuildKey key = (NamedTypeBuildKey) context.BuildKey;
         if (_factoryProducedTypes.Contains(key.Type))
         {
            if (key.Name != null)
            {
               context.Locator.Add("key", key.Name);
            }
            context.BuildKey = new NamedTypeBuildKey(key.Type);
         }
      }
   }
}
